package com.gsit.expenditure.controller;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;

import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import com.gsit.expenditure.client.domina.CustomerBean;
import com.gsit.expenditure.client.domina.FXMLBase;
import com.gsit.expenditure.domain.Customer;
import com.gsit.expenditure.services.CustomerService;
import com.gsit.expenditure.utils.AppContextLoader;
import com.gsit.expenditure.utils.Page;
import com.gsit.expenditure.utils.Utils;
import com.gsit.expenditure.utils.ViewHandler;

public class CustomerController extends BaseController implements Initializable {

	@FXML private TextField firstNameText;
	@FXML private TextField lastNameText;
	@FXML private TextField emailText;
	@FXML private TextField address1Text;
	@FXML private TextField address2Text;
	@FXML private TextField cityText;
	@FXML private TextField stateText;
	@FXML private TextField countryText;
	@FXML private TextField pinCodeText;
	@FXML private TextField phoneText;
	@FXML private TextField mobileText;

	@FXML private Label firstNameErrorLabel;
	@FXML private Label lastNameErrorLabel ;
	@FXML private Label emailErrorLabel ;
	@FXML private Label addressErrorLabel ;
	@FXML private Label cityErroLabel;
	@FXML private Label stateErrorLabel;
	@FXML private Label countryErroLabel;
	@FXML private Label pinErrorLabel;
	@FXML private Label phoneErrorLabe;
	
	@FXML private Label mobileErrorLabel ;
	
	@FXML private Button saveButton;
	@FXML private Button clearButton;

	private CustomerBean customerBean;
	private CustomerService customerService;
	private Customer customer;

	private Validator validator;
	
	
	@Override
	public void initialize(URL url, ResourceBundle bundle) {
		customerService = AppContextLoader.getBean(CustomerService.class);
		customerBean = new CustomerBean(customer);
		init();
		bind();
	}

	private void bind() {
		
		Bindings.bindBidirectional(customerBean.getFirstName(),firstNameText.textProperty());
		Bindings.bindBidirectional(customerBean.getLastName(),lastNameText.textProperty());
		Bindings.bindBidirectional(customerBean.getEmail(),emailText.textProperty());
		Bindings.bindBidirectional(customerBean.getAddress1(),address1Text.textProperty());
		Bindings.bindBidirectional(customerBean.getAddress2(),address2Text.textProperty());
		Bindings.bindBidirectional(customerBean.getCity(),cityText.textProperty());
		Bindings.bindBidirectional(customerBean.getState(),stateText.textProperty());
		Bindings.bindBidirectional(customerBean.getCountry(),countryText.textProperty());
		Bindings.bindBidirectional(customerBean.getLastName(),lastNameText.textProperty());
		Bindings.bindBidirectional(customerBean.getPhone(),phoneText.textProperty());
		Bindings.bindBidirectional(customerBean.getMobile(),mobileText.textProperty());
		Bindings.bindBidirectional(customerBean.getPinCode(),pinCodeText.textProperty());

	}

	@Override
	@FXML
	public void onSave() {
		
		Boolean isUpdate = Boolean.FALSE;
		
		 if(isValid()) {
			 if (firstNameText.toString().trim().matches("\\'+=.")) {
				 phoneErrorLabe.setText("Invalid characters"); 
			 }else{
			 
			if (customer.getId() != null && customer.getId().longValue() > 0) {
				isUpdate = Boolean.TRUE;
				Customer customer = customerBean.getObject();
				customer.setModifiedDate(Utils.getCurrentDate());
				//customer.setVersion(1L);
				customer = customerService.saveOrUpdate(customer);
				
			}else{
				
				Customer customer = customerBean.getObject();
				customer.setCreatedDate(Utils.getCurrentDate());
				customer.setModifiedDate(Utils.getCurrentDate());
				//customer.setVersion(1L);
				
				customer = customerService.saveOrUpdate(customer);
				System.out.println("CustName>>>>>>>>>>>"+customer.getFirstName());
				if(customer.getId() != null && customer.getId().longValue() > 0){
					showCustomerPopup(customer);
				}
			}
			 }
			
			if (isUpdate) {
				stateChange.set(Boolean.TRUE);
			}
		}
	}
	
	private void showCustomerPopup(Customer customer){
		final FXMLBase<SuccessController> fxmlBase =  ViewHandler.createFXMLBase(Page.SUCCESS_MSG);
		fxmlBase.getController().getStateChange().addListener(new ChangeListener<Boolean>() {
			@Override
			public void changed(ObservableValue<? extends Boolean> arg0,Boolean oldVal, Boolean newVal) {
				if(newVal){
					fxmlBase.getDialogStage().hide();
					MainAppController.loadNext(Page.SEARCH_CUSTOMER);
		
				}
			}
		});
	
		ViewHandler.createDialog(fxmlBase, "Customer has been successfully created");
		fxmlBase.getDialogStage().showAndWait();
	}
	
	private Boolean isValid(){
		clearErrorLabel();
		Boolean result =Boolean.TRUE;
		
		validator = Validation.buildDefaultValidatorFactory().getValidator();

		Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customerBean.getObject());
		System.out.println("Error Values>>>>>>>>>>>"+customerBean.getObject());
		
		for (ConstraintViolation<Customer> constraintViolation : constraintViolations) {
			if ("firstName".equalsIgnoreCase(constraintViolation
					.getPropertyPath().toString())) {
				firstNameErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("lastName".equalsIgnoreCase(constraintViolation
					.getPropertyPath().toString())) {
				lastNameErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("email".equalsIgnoreCase(constraintViolation.getPropertyPath()
					.toString())) {
				emailErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("address.address1".equalsIgnoreCase(constraintViolation.getPropertyPath()
					.toString())) {
				addressErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("address.city".equalsIgnoreCase(constraintViolation.getPropertyPath()
					.toString())) {
				cityErroLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("address.state".equalsIgnoreCase(constraintViolation.getPropertyPath()
					.toString())) {
				stateErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("address.country".equalsIgnoreCase(constraintViolation
					.getPropertyPath().toString())) {
				countryErroLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("address.pinCode".equalsIgnoreCase(constraintViolation
					.getPropertyPath().toString())) {
				pinErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			if ("phone".equalsIgnoreCase(constraintViolation
					.getPropertyPath().toString())) {
				phoneErrorLabe.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
			
			
			if ("mobile".equalsIgnoreCase(constraintViolation.getPropertyPath()
					.toString())) {
				mobileErrorLabel.setText(constraintViolation.getMessage());
				result = Boolean.FALSE;
			}
		}
		return result;
	}
	
	
	private void clearErrorLabel(){
			phoneErrorLabe.setText("");
		 firstNameErrorLabel.setText("");
		 lastNameErrorLabel.setText("");
		 emailErrorLabel.setText("");
		 addressErrorLabel.setText("");
		 cityErroLabel.setText("");
		 stateErrorLabel.setText("");
		countryErroLabel.setText("");
		pinErrorLabel.setText("");
		
		 mobileErrorLabel.setText("");
	}

	@Override
	public void onClear() {

		Long id = customerBean.getCustomer().getId();
		if (customer.getId() != null && customer.getId().longValue() > 0) {
			Customer customer = customerService.find(Customer.class, id);
			customerBean.reLoad(customer);
		} else {
			customerBean.clean();
		}
	}
	
	private void init() {
		if (this.customerBean.getCustomer() == null)
			return;
		
		this.customer = this.customerBean.getCustomer();
		firstNameText.setText(customer.getFirstName());
		lastNameText.setText(customer.getLastName());
		emailText.setText(customer.getEmail());
		phoneText.setText(customer.getPhone());
		mobileText.setText(customer.getMobile());
		if (customer.getAddress() != null) {
			address1Text.setText(customer.getAddress().getAddress1());
			address2Text.setText(customer.getAddress().getAddress2());
			cityText.setText(customer.getAddress().getCity());
			stateText.setText(customer.getAddress().getState());
			countryText.setText(customer.getAddress().getCountry());
			pinCodeText.setText(customer.getAddress().getPinCode());
		}

	}

	public void reLoad(CustomerBean customerBean) {
		this.customerBean = customerBean;
		init();
		bind();
	}
	
}
